import React, { Component } from 'react';
import _ from 'lodash';
import { Text, View, Picker } from 'react-native';
import styles from '../styles';
import { parseErrors } from '../..'
import StatusIcon from "../../statusIcon";
import SelectValue from '../selectValue';

// const styles = {}
export default class Selecter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.initialValue || '',
      tempValue: '',
      initialValue: props.initialValue,
      valueSize: {},
    };
  }
  componentWillReceiveProps(next) {
    if ((next.value !== this.props.value)) {
      this.setState({
        value: next.value
      }, () => {
        if (_.isFunction(this.props.afterChange)) {
          this.props.afterChange(next.value)
        }
      })
    }
  }
  onChange = value => {
    this.props.onChange(value);
  };
  options = (opts) => {
    const _opts = _.cloneDeep(opts);
    _opts.unshift({ label: '请选择', value: '' })
    return _.map(_opts, ({ label, value, fieldKey }, i) => {
      return <Picker.Item key={`${fieldKey}_${value}_${i}`} label={label} value={value} />
    })
  }
  getLabel = (opts, value) => {
    const target = _.find(opts, ['value', value]);
    if (target) {
      return target.label;
    }
    return '';
  }
  onLayout = (e) => {
    const { nativeEvent: { layout: { width, height } } } = e;
    this.setState({
      valueSize: { width, height }
    });
  }

  render() {
    if(!styles){
      return null
    }
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>{this.props.label}</Text>
        </View>
        <View style={styles.value} onLayout={this.onLayout}>
          <SelectValue
            value={this.state.value}
            placeholder={this.props.placeholder}
            fn={this.getLabel.bind(null, this.props.options)}
          />
          <Picker
            selectedValue={this.props.value}
            onValueChange={this.onChange}
            style={[styles.pickerEmiter, {
              width: this.state.valueSize.width,
              height: this.state.valueSize.height,
            }]}
            value={this.props.value}
          >
            {this.options(this.props.options)}
          </Picker>
        </View>
        {this.props.error ? <StatusIcon type="error" msg={parseErrors(this.props.error)} /> : null}
      </View>
    )
  }
}